Ext.define("Triends.Tinglist",{
	extend: "Ext.data.Model",
	config: {
		idProperty: "NUMBER",
		fields: ["NUMBER", "ID", "HOST", "TITLE", "THEME", "LAT", "LNG", "CONTENT", "DATE", "AMPMDATE", "TIME", "Distance", "Time", "ThemeScore", "Total", "Wifi"]
	}
});

Ext.define("Triends.TingMaplist",{
	extend: "Ext.data.Model",
	config: {
		fields: ["NUMBER", "ID", "HOST", "TITLE", "THEME", "LAT", "LNG", "CONTENT", "DATE", "TIME"]
	}
});

var tingStore = Ext.create("Ext.data.Store",{
	model: "Triends.Tinglist",
	id: 'tingstore',
	pageSize: 20,
	clearOnPageLoad: false
//	sorters: [
//		{
//			property: 'STARTDATE',
//			direction: 'ASC'
//		},
//		{
//			property: 'STARTTIME',
//			direction: 'ASC'
//		}
//	]
});

var tingMapStore = Ext.create("Ext.data.Store",{
	model: "Triends.TingMaplist",
	id: 'tingmapstore'
});


Ext.define('Triends.view.Tinglist', {
	extend: 'Ext.dataview.DataView',
	id: 'tinglist',
	xtype: 'tinglist',
	config: {
		fullscreen: true,
//		layout: 'vbox',
		store: tingStore,
		useComponents: true,
//		scrollable: true,
		style: 'background:white',
		defaultType: 'TingListItem',
		loadingText: false,
		listeners: {
			initialize: function() {

    			var wrapper = this.getScrollable().getElement();
   				
   				var unloader = new Unloader(wrapper, '.x-container x-data-item');

				var masterScroll = new iScroll(wrapper.getId(), {
    				onRefresh: function() {
        				unloader.setup(this.x, this.y);
    				},
    				onPositionChange: function(x, y) {
        				unloader.onmove(x, y); 
    				}
				});
				this.getScrollable().setScroller(masterScroll);
							
			}
		},
		plugins: [
				{type: 'listpaging', autoPaging:true, clearOnPageLoad: false, loadMoreText: 'Next..'},
				{type: 'pullrefresh' /*refreshFn: function(plugin){postStore.load()}*/}
		],
		limit: 20,
		items: [
		{
			xtype: 'titlebar',
			height: 48,
			docked: 'top',
			ui: 'light',
			items: [
			{
				xtype: 'button',
				id: 'tingopenbtn',
				height: 20,
				align: 'left',
				text: 'Ting Open',
				handler: function(){
					try {
						var userid = Ext.getStore("UserStore").getAt(0).data.ID;
						Ext.getCmp("tingdate").setValue(new Date());
						Triends.app.getHistory().add(Ext.create('Ext.app.Action', {
							url: 'mainpage/ting/tingopen'
						}));
					} catch(e){
						navigator.notification.confirm(
							'로그인이 필요합니다.',
							function(){},
							'알림',
							'확인'
						)
					} 
				}
			},
			{
				xtype: 'panel',
				id: 'tingthemeimg',
				align: 'right',
				height: 25,
				width: 25
			},
			{
 				 xtype: 'selectfield',
				 align: 'right',
				 width: 120,
				 inputCls: 'selectfield',
				 usePicker: false,
				 id: 'tinglisttheme',
				 options: [
			 		{text: '식사', value: 1},
			 		{text: '술', value: 2},
			 		{text: '야경', value: 3},
			 		{text: '공연관람', value: 4},
			 		{text: '쇼핑', value: 5},
			 		{text: '클러빙', value: 6},
			 		{text: '전체', value: 7}
			 	 ],
			 	 listeners:{
			 	 	change: function(selectbox, newValue, oldValue){
			 	 		var usertheme = newValue.get('value');
			 	 			Ext.getCmp('tingthemeimg').setHtml('<img src="resource/images/'+usertheme+'.png" width="25px" height="25px">');
						// TingList에서 테마를 변경한 경우 - TriendsList 테마 바꾸기 실행
						if (usertheme != Ext.getCmp('triendslisttheme').getValue()) {
	           				Ext.getCmp('triendslisttheme').setValue(usertheme);
	           			}
					}		
			 	 }
			}]
		}]
	}	
});


Ext.define('TingListItem', {
	extend: 'Ext.dataview.component.DataItem',
    xtype: 'TingListItem',
	config: {
		listeners: {
			updatedata: function() {
				var data = this.getRecord();
				var theme = this.getRecord().get('THEME');
				var img = this.getItems().items[0].getItems().items[0];
				img.setHtml("<img src='resource/images/"+theme+".png' width='48px' height='48px'>");
				
				
				var titlepanel = this.getItems().items[1].getItems().items[0];
				var datepanel = this.getItems().items[1].getItems().items[1];
				var tfipicturepanel = this.getItems().items[3].getItems().items[0];
				var title = this.getRecord().get('TITLE');
				var date = this.getRecord().get('DATE').split(' ')[0];
				var hour = this.getRecord().get('DATE').split(' ')[1].substr(0,2);
				var minute = this.getRecord().get('DATE').split(' ')[1].substr(2);
				var ampm;
				if(hour >= 12){
					hour = hour-12;
					ampm = "PM"
				} else{
					ampm = "AM"
				}
				titlepanel.setHtml("<font size='3'><b>"+title+"</b></font>");
				datepanel.setHtml("<font size='2'>"+date+" "+ampm+" "+hour+""+minute+"</font>");
				var Tvalue = this.getRecord().get('Total');
				var Tpanel = this.getItems().items[2];
				Tpanel.setHtml("<font size='2'><b>"+Tvalue+"%</b></font>");
				
				var wifi = this.getRecord().get('Wifi');
				tfipicturepanel.setHtml("<img src='resource/images/wifi"+wifi+".png' width='40px' height='40px'>");
			}
		},
		layout: 'hbox',
		width: '100%',
		minHeight: 80,
		style: 'background:white;border-bottom:1px #CBCAC7 solid;',
		items: [
		{
			xtype: 'panel',
			width: 80,
			style: 'padding-top: 15px; padding-left: 15px; ',
			listeners: {
				tap: {
					element: 'element',
					fn: function() {
						Ext.Viewport.setMasked({
							xtype: 'loadmask',
					    	indicator: true
						});
						var dataitem = this.getParent();	
						dataitem.setStyle("background:#CBCAC7");
						setTimeout(function(){dataitem.setStyle('background:white;border-bottom:1px #CBCAC7 solid;')},200);
						
						setTimeout(function(){
							var userid = Ext.getStore("UserStore").getAt(0).data.ID;
							
							var model = dataitem.getRecord();
							var tingnum = model.get('NUMBER');
							openTinginfo(model, tingnum);
							
						}, 500);
					}
				}
			},
			items:[{
				xtype: 'panel',
				height: 48,
				width: 48
			}]
		},
		{
			xtype: 'panel',
			flex: 4,
			style: 'padding-bottom:10px; ',
			layout: 'vbox',
			listeners: {
				tap: {
					element: 'element',
					fn: function() {
						Ext.Viewport.setMasked({
							xtype: 'loadmask',
					    	indicator: true
						});
						var dataitem = this.getParent();	
						dataitem.setStyle("background:#CBCAC7");
						setTimeout(function(){dataitem.setStyle('background:white;border-bottom:1px #CBCAC7 solid;')},200);
						
						setTimeout(function(){
							var userid = Ext.getStore("UserStore").getAt(0).data.ID;
							
							var model = dataitem.getRecord();
							var tingnum = model.get('NUMBER');
								
							openTinginfo(model, tingnum);
						}, 500);
					}
				}
			},
			items: [{
				xtype: 'panel',
				style: 'word-break:break-all;padding-top:10px; '
			},
			{
				xtype: 'panel',
				style: 'margin-top:10px; ',
				listeners: {
					tap: {
						element: 'element',
						fn: function() {
							var userid = Ext.getStore("UserStore").getAt(0).data.ID;
							
							var dataitem = this.getParent().getParent();
							var model = dataitem.getRecord();
							var tingnum = dataitem.getRecord().get('NUMBER');
							
							openTinginfo(model, tingnum);
						}
					}
				}
			}]
		},
		{
			xtype: 'panel',
			width: 48,
			style: 'word-break:break-all;padding-right:10px;padding-top:30px;text-align:center; ',
			docked: 'right',
			listeners: {
				tap: {
					element: 'element',
					fn: function() {
						var dataitem = this.getParent();
						var record = dataitem.getRecord();
						
						var Tdetail = Ext.create('Triends.view.Tfidetail');
						var Tfidistance = Ext.getCmp('Tfidistance1');
						var Tfitime = Ext.getCmp('Tfitime1');
						var Tfitheme = Ext.getCmp('Tfitheme1');
						var distance = record.get("Distance").split(".")[0];
				    	var time = record.get("Time").split(".")[0];
				    	if (time.match("-") != null){
				    		time = time.replace("-", "");
				    		if (time < 60){
					    		Tfitime.setHtml("<font size='5'>"+time+"</font>분")
					    	}else if(time > 60 && time < 1440){
					    		time = time/60;
					    		time = Math.round(time);
					    		Tfitime.setHtml("<font size='5'>"+time+"</font>시간")
					    	}else if(time > 1440){
					    		time = time/1440;
					    		time = Math.round(time);
					    		Tfitime.setHtml("<font size='5'>"+time+"</font>일")
					    	}
				    	} else{
				    		Tfitime.setHtml("모임시간이 지났습니다")
				    	}
				    	var theme = record.get("THEME");
				    	Tfidistance.setData({Distance: distance});
				    	Tfitheme.setHtml('<img src="resource/images/'+theme+'.png">');
				    	Ext.Viewport.add(Tdetail);
					}
				}
			}
		},
		{
			xtype: 'panel',
			layout: 'vbox',
			style: 'margin-left:5px;margin-right:5px; ',
			items:[{
				xtype: 'panel',
				style: 'margin-top:10px; ',
				width: 40,
				listeners: {
						tap: {
							element: 'element',
							fn: function() {
								var dataitem = this.getParent().getParent();
								var record = dataitem.getRecord();
								
								var Tdetail = Ext.create('Triends.view.Tfidetail');
								var Tfidistance = Ext.getCmp('Tfidistance1');
								var Tfitime = Ext.getCmp('Tfitime1');
								var Tfitheme = Ext.getCmp('Tfitheme1');
								var distance = record.get("Distance").split(".")[0];
						    	var time = record.get("Time").split(".")[0];
						    	if (time.match("-") != null){
						    		time = time.replace("-", "");
						    		if (time < 60){
							    		Tfitime.setHtml("<font size='5'>"+time+"</font>분")
							    	}else if(time > 60 && time < 1440){
							    		time = time/60;
							    		time = Math.round(time);
							    		Tfitime.setHtml("<font size='5'>"+time+"</font>시간")
							    	}else if(time > 1440){
							    		time = time/1440;
							    		time = Math.round(time);
							    		Tfitime.setHtml("<font size='5'>"+time+"</font>일")
							    	}
						    	} else {
						    		Tfitime.setHtml("모임시간이 지났습니다")
						    	}
						    	var theme = record.get("THEME");
						    	Tfidistance.setData({Distance: distance});
						    	Tfitheme.setHtml('<img src="resource/images/'+theme+'.png">');
						    	Ext.Viewport.add(Tdetail);
							}
						}
				}
			},
			{
				xtype: 'panel',
				style: 'text-align:center;margin-top:-10px; ',
				html: 'T-fi',
				listeners: {
						tap: {
							element: 'element',
							fn: function() {
								var dataitem = this.getParent().getParent();
								var record = dataitem.getRecord();
								
								var Tdetail = Ext.create('Triends.view.Tfidetail');
								var Tfidistance = Ext.getCmp('Tfidistance1');
								var Tfitime = Ext.getCmp('Tfitime1');
								var Tfitheme = Ext.getCmp('Tfitheme1');
								var distance = record.get("Distance").split(".")[0];
						    	var time = record.get("Time").split(".")[0];
						    	if (time.match("-") != null){
						    		time = time.replace("-", "");
						    		if (time < 60){
							    		Tfitime.setHtml("<font size='5'>"+time+"</font>분")
							    	}else if(time > 60 && time < 1440){
							    		time = time/60;
							    		time = Math.round(time);
							    		Tfitime.setHtml("<font size='5'>"+time+"</font>시간")
							    	}else if(time > 1440){
							    		time = time/1440;
							    		time = Math.round(time);
							    		Tfitime.setHtml("<font size='5'>"+time+"</font>일")
							    	}
						    	} else{
						    		Tfitime.setHtml("모임시간이 지났습니다")
						    	}
						    	var theme = record.get("THEME");
						    	Tfidistance.setData({Distance: distance});
						    	Tfitheme.setHtml('<img src="resource/images/'+theme+'.png">');
						    	Ext.Viewport.add(Tdetail);
							}
						}
				}
			}]
    	}]
	}
});

Ext.define('Triends.view.Tfidetail', {
	extend: 'Ext.Panel',
	xtype: 'Tfidetail',
	id: 'Tfidetail',
	config: {
    	modal: true,
    	top: '10%',
    	left: '50%',
    	layout: 'vbox',
    	style: 'margin-left:-150px',
		hideOnMaskTap: true,
		width: 300,
		height: 350,
		listeners: {
			hide: function() {
				this.destroy();
			}
		},
    	items: [{
    		xtype: 'titlebar',
    		docked: 'top',
    		title: '<div class="title"><font size="3">T-fi 구성요소</font></div>'
    	},
    	{
    		xtype: 'panel',
    		style: 'padding:10px',
    		layout: 'vbox',
    		items: [{
    			xtype: 'panel',
    			html: '<font size="3"><b>거리</b></font>'
    		},
    		{
    			xtype: 'panel',
    			id: 'Tfidistance1',
    			width: '100%',
    			style: 'margin-top:10px;text-align:center',
    			tpl: "<font size='5'>{Distance}</font> km"
    		},
    		{
    			xtype: 'panel',
    			style: 'margin-top:30px',
    			html: '<font size="3"><b>모임까지 남은 시간</b></font>'
    		},
    		{
    			xtype: 'panel',
    			id: 'Tfitime1',
    			width: '100%',
    			style: 'margin-top:10px;text-align:center'
    		},
    		{
    			xtype: 'panel',
    			style: 'margin-top:30px',
    			html: '<font size="3"><b>Theme</b></font>'
    		},
    		{
    			xtype: 'panel',
    			width: '100%',
    			items:[{
    				xtype: 'panel',
		    		style: 'left:50%; margin-left:-24px',
	    			id: 'Tfitheme1',
	    			width: 48
    			}]
    		}]
    	}]
	}
});


		/*var map;

		var geocoder;
		geocoder = new google.maps.Geocoder();
		
		var mapsearchlatlng, mapsearchlat, mapsearchlng;
		
		var latlng = new google.maps.LatLng(37.55575425229087, 126.93629264831543);
		
		var marker, markerlat, markerlng;
		
		var tinglist = Ext.getCmp("tinglist");
					  
		function mapsearchresult(){
			 var address = Ext.getCmp("mapsearch").getValue();
       			 geocoder.geocode( { 'address': address}, function(results, status) {
          			if (status == google.maps.GeocoderStatus.OK) {
          				mapsearchlatlng = results[0].geometry.location;
          				mapsearchlat = mapsearchlatlng.lat();
          				mapsearchlng = mapsearchlatlng.lng();
          				setTimeout("listcall(mapsearchlat, mapsearchlng)",100);
          			} else {
            			alert('Geocode was not successful for the following reason: ' + status);
          			}
        		});
        	}
		
		function listcall(mapsearchlat, mapsearchlng){
    			
				tingStore.removeAll();
    			tingStore.setProxy({
					type: "jsonp",
					url: 'http://itscreater.cafe24.com/Triends/TingList.jsp',
					extraParams: {mapsearchlat:mapsearchlat, mapsearchlng:mapsearchlng},
					callbackkey: 'callback',
					pageParam: 'pages',
					limitParam: 'rpp',
					reader: {
						type: "json",
						rootProperty: "results",
						totalProperty: "total"
					}
				});
				tingStore.loadPage(1);*/
				
//				Ext.data.JsonP.request({
//					url: 'http://itscreater.cafe24.com/Triends/TingMapList.jsp',
//					params: {mapsearchlat:mapsearchlat, mapsearchlng:mapsearchlng}, 
//					callbackkey: 'callback',
//					success: function(result){
//						 tingMapStore.setData(result);
//						
//						 map = Ext.create("Ext.Map",{
//							xtype: "map",
//							mapOptions: {
//								center: mapsearchlatlng,
//								zoom: 11,
//								zoomControl: true,
//								mapTypeId: google.maps.MapTypeId.ROADMAP,
//								navigationControl: true,
//								streetViewControl: false,
//								mapTypeControl: false,
//								navigationControlOptions:{style: google.maps.NavigationControlStyle.DEFAULT}
//							},
//							listeners: {
//								maprender: function (comp, map){
//									for(i=0; i<result.length; i++){
//										var tinglistdata = result[i];
//										var markerlat = tinglistdata.LAT;
//										var markerlng = tinglistdata.LNG;
//										var infoContent = "<h2 class='phoneytext'>"+tinglistdata.TITLE+"</h2>";
//										var currentInfo = '';
//										var markerposition = new google.maps.LatLng(markerlat, markerlng);
//										var marker= new google.maps.Marker({
//											position: markerposition,
//											map: map,
//											icon: 'resource/images/mappin1.png'
//										});
//										marker['infobubble'] = new InfoBubble({
//											content: infoContent,
//											shadowStyle: 1,
//									        padding: 0,
//									        backgroundColor: 'rgb(57,57,57)', // 이걸 바꿔줘야 말풍선 꼬리 색깔이 바뀐다.
//									        borderRadius: 4,
//									        arrowSize: 10,
//									        borderWidth: 1,
//									        borderColor: 'rgb(57,57,57)', 
//									        hideCloseButton: true,
//									        arrowPosition: 30,
//									        backgroundClassName: 'phoney',
//									        arrowStyle: 2
//										});
//										marker['data'] = tingMapStore.findRecord('NUMBER', tinglistdata.NUMBER); // data값을 달아주고,
//										
//										google.maps.event.addListener(marker, 'click', function(){
//											if(currentInfo != ''){
//												currentInfo.close();
//												currentInfo = '';
//											}
//											this['infobubble'].open(map, this);
//											currentInfo = this['infobubble']; // 여기까지가 다른 마커 클릭하면 현재 인포창 닫는 역할 
//											
//											var model = this['data']; // 해당 마커에 해당하는 data값만 가져다 쓴다.
//											var tingnum = model.data.NUMBER;
//											google.maps.event.addDomListener(this['infobubble'].bubble_, 'click', function(){
//												try {
//		        									var userid = Ext.getStore("UserStore").getAt(0).data.ID;
//													openTinginfo(model, tingnum);
//													
//													var kind = 'maptingclick';
//													Ext.data.JsonP.request({
//														url: 'http://itscreater.cafe24.com/Triends/Counting.jsp',
//										    			params: {kind: kind, num:tingnum},
//										    			callbackKey: 'callback',
//										    			success: function(){
//										    			}
//													})
//	        									} catch(e){
//	        										Ext.Msg.alert("","로그인이 필요합니다");
//	        	} 
//												
//											}); // 여기까지가 인포창 클릭했을 때 해당하는 data를 tinginfo에 넘겨주고 tinginfo로 화면전환
//											
//											google.maps.event.addListener(map, 'mousedown', function(){
//											currentInfo.close();
//											}) // 맵을 클릭했을 경우 현재 인포창 닫기 
//										});
//									}
//									
//								}
//							}
//						});
//						var tinglist = Ext.getCmp("tinglist");
//						tinglist.add(map);
//        				}
//        			});	
//        			
//
